package com.nvwa.word;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * WordHelper 类。
 *
 * @author wangjing
 * @date 2024-12-05 [wangjing] 创建。
 */
public class WordHelper {

    /**
     * 通过Word模板导出Word文档
     *
     * @param placeholders     模板中占位符和值，key：占位符，value：值
     * @param templateFileName resrouces目录下模板文件名，示例：phonemodel.doc
     * @param newFileName      导出后文件新名称
     * @return ResponseEntity
     */
    public static ResponseEntity<byte[]> export(Map<String, String> placeholders, String templateFileName, String newFileName) throws IOException {
        //读取模板
        ClassPathResource resource = new ClassPathResource(templateFileName);
        //初始化占位符和参数
        InputStream inputStream = resource.getInputStream();
        HWPFDocument document = new HWPFDocument(inputStream);
        Range bodyRange = document.getRange();
        //替换占位符
        for (Map.Entry<String, String> entry : placeholders.entrySet()) {
            bodyRange.replaceText(entry.getKey(), entry.getValue());
        }
        //写到stream中
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        document.write(ostream);
        //写到response中
        ResponseEntity<byte[]> body = ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + newFileName + ".doc")
                .body(ostream.toByteArray());

        return body;
    }

}
